package com.starblink.library.widget.product

import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.starblink.android.basic.adapter.BaseVH
import com.starblink.android.basic.data.model.product.ProductFWrap
import com.starblink.android.basic.sensorsdata.exposure.isInScreen
import com.starblink.android.basic.util.CoroutineUpdateTask
import com.starblink.library.widget.product.util.TrackUtil

class SimpleProductCardCell(
    private val refreshLayout: SmartRefreshLayout,
    private val recyclerView: RecyclerView,
    parent: ViewGroup,
    private val feedsScene: ProductCardScene? = null,
    var pageTrackTag: String? = null,
    var searchWord: String? = null, // 搜索词(仅文搜商品卡片使用)
    var searchWordSource: Int? = null, // 搜索词来源(仅文搜商品卡片使用)
) :
    BaseVH<ProductFWrap>(ProductCardView(parent.context)) {

    private companion object {
        const val TAG = "SimpleProductCardCell"
    }

    private val cardView = itemView as ProductCardView

    override fun onBind(model: ProductFWrap, position: Int) {
        //Log.d(TAG, "onBind: position: ${position}, name: ${model.title}")
        cardView.scene = feedsScene
        cardView.bindProduct(
            refreshLayout=refreshLayout,
            recyclerView=recyclerView,
            productWrap = model,
            spmPageValue = TrackUtil.transformPageValue(scene = feedsScene),
            position = position,
            searchWord = searchWord,
            searchWordSource = searchWordSource,
            guideType = TAG
        )
    }

    private var task: CoroutineUpdateTask? = null
    private fun handleGuide(view: ViewGroup, showGuide: ((ViewGroup, View) -> Unit)? = null) {
        if (task == null) {
            task = CoroutineUpdateTask()
            task?.scheduleUpdate(500, action = {
                view.post {
                    var anchorView =
                        view.findViewById<ImageView>(com.starblink.library.widget.R.id.img)
                    if (anchorView.isInScreen()) {
                        anchorView.postDelayed(
                            { showGuide?.invoke(view, anchorView) }, 500
                        )
                        task?.cancel()
                    }
                }
            })
        }
    }
}